import {
    View, FlatList, RefreshControl, TouchableOpacity, AsyncStorage,
    TouchableHighlight, Text, StyleSheet, Image, Alert, DatePickerAndroid
} from 'react-native';
import React, {PureComponent} from 'react';
import Urls, {getRealUrl, postRealUrl} from '../const/Urls'
import LocalImg from '../const/Images'
import moment from 'moment'
import {Modal, Button, WingBlank, WhiteSpace, Toast} from 'antd-mobile-rn';

const prompt = Modal.prompt;

/*
 * 引航员记事
 */
class PageYhyjs extends PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            user: {
                token: '',
                pilotCode: '',
                pilotName: '',
                bmbm: '',
                pilotID:'',
            },
            data: [],
            isLoading: false,
        };
        this.setUser();
    }

    componentDidMount() {
        this.setState({
            data: [],
        });
        this.setUser();
    }

    setUser() {
        AsyncStorage.getItem("user", (error, result) => {
            if (!error) {

                const data = JSON.parse(result);
                if (data) {
                    this.setState({
                        user: {
                            token: data['token'],
                            pilotCode: data['pilotCode'],
                            pilotName: data['pilotName'],
                            bmbm: data['bmbm'],
                            pilotID:data['pilotID']
                        }
                    });
                    this.loadData();
                } else {
                    this.setState({
                        user: {
                            token: '',
                            pilotCode: '',
                            pilotName: '',
                            bmbm: '',
                            pilotID:''
                        }
                    });
                }
            }
        })
    }

    render() {
        return (
            <View style={{flexDirection: 'column', flex: 1}}>

                <View style={{
                    flexDirection: 'row',
                    flex: 0,
                    height: 60,
                    alignItems: 'center',
                    justifyContent: 'center',
                    backgroundColor: '#0066FF'
                }}>
                    <View style={{flex: 1, padding: 10}}>
                        <TouchableOpacity onPress={() => this.props.navigation.pop()}>
                            <Image source={LocalImg['backImg']} style={{height: 30, width: 30, resizeMode: 'contain'}}/>
                        </TouchableOpacity>
                    </View>
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={{fontSize: 20, color: '#ffffff'}}>引航员记事</Text>
                    </View>

                    <View style={{flex: 1, alignItems: 'flex-end', padding: 10}}>

                    </View>
                </View>

                <View style={{height: 1, backgroundColor: '#CCCCCC'}}/>

                <View style={{
                    flexDirection: 'row',
                    backgroundColor: '#f9f9f9',
                    padding: 6,
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}>船名</Text>
                    </View>
                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}>代理</Text>
                    </View>
                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}>状态</Text>
                    </View>

                </View>

                <View style={{
                    flexDirection: 'row',
                    backgroundColor: '#f9f9f9',
                    padding: 6,
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}></Text>
                    </View>
                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}>引   航   任   务</Text>
                    </View>
                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}></Text>
                    </View>
                </View>


                <View style={{
                    flexDirection: 'row',
                    backgroundColor: '#f9f9f9',
                    padding: 6,
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>

                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}>记事内容</Text>
                    </View>
                    <View style={{flex: 1}}>
                        <Text style={{fontWeight: 'bold'}}>操作</Text>
                    </View>
                </View>

                <FlatList
                    data={this.state.data}
                    renderItem={(item, index) => this.renderRow(item, index)}
                    keyExtractor={this.keyExtractor}
                    ItemSeparatorComponent={this.separator}
                    ListFooterComponent={() => this.footerView()}
                    onEndReachedThreshold={0.1}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isLoading}
                            onRefresh={() => this.onRefresh()}
                        />
                    }/>

            </View>
        )
    }

    keyExtractor = (item, index) => item.YHYID + "";

    footerView() {
        return (
            <View style={{flexDirection: 'row', justifyContent: 'center', paddingTop: 20, paddingBottom: 30}}>
                <Text>到底了</Text>
            </View>
        )
    }


    onRefresh() {
        this.setState({
            data: [],
        });
        this.loadData();
    }


    loadData() {
        this.setState({
            isLoading: true
        });

        const request = new Map();
        //request.set('yhycode', 10);
        request.set('yhycode', this.state.user['pilotID']);
        //alert(this.state.user['pilotID']);

        fetch(getRealUrl(Urls['yhyjsUrl'], request), {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson instanceof Array) {
                    this.setState({
                        data: responseJson,
                    });
                }
                this.setState({
                    isLoading: false,
                });

            })
            .catch(error => {
                console.error(error);
                this.setState({
                    isLoading: false
                });
            });


    }

    separator(index) {
        return (
            <View key={index} style={{height: 1, backgroundColor: '#CCCCCC'}}/>
        )
    }

    processDateTime(date) {
        const m = moment(date);
        if (m.isValid()) {
            return m.format('DD/HHmm')
        } else
            return ""
    }


    getFormatDate(date) {
        const m = moment(date);
        if (m.isValid()) {
            return m.format('YYYY-MM-DD')
        } else
            return ""
    }


    renderRow({item, index}) {
        let bColor = index % 2 !== 0 ? "#f9f9f9" : "#ffffff";
        let show = item.VCDOCKNAME === '' && parseInt(item.CHDOCKCODE) === 0;
        let style = 'flex';
        if (show) {
            style = 'none'
        }
        return (
            <TouchableHighlight key={item.CHDOCKCODE} style={{display: style}}>
                <View style={[styles.text, {flex: 1, marginLeft: 10, marginTop: 10, justifyContent: 'center'}]}>
                    <View style={{flex: 1, flexDirection: 'row'}}>
                        <View style={{flex: 1}}>
                            <Text>{item.ship_name_cn}</Text>
                        </View>
                        <View style={{flex: 1}}>
                            <Text>  {item.agentdw_name}  </Text>
                        </View>
                        <View style={{flex: 1}}>
                            <Text>{item.statusname}</Text>
                        </View>
                    </View>

                    <WhiteSpace size="lg"/>
                    <View style={{flex: 1, flexDirection: 'row'}}>
                        <View style={{flex: 1}}>
                            <Text>{item.dtqk}</Text>
                        </View>
                    </View>
                    <WhiteSpace size="lg"/>


                    <View style={{flex: 1, flexDirection: 'row', alignItems: 'flex-end'}}>
                        <View style={{flex: 1}}>
                            <Text>{item.pilot_record}</Text>
                        </View>

                        <View style={{flex: 1, flexDirection: 'row-reverse'}}>

                            <TouchableHighlight underlayColor='white'
                                                style={{paddingRight: 10}}
                                                onPress={() => prompt('引航记事', '请输入状态信息', [
                                                    {text: '取消'},
                                                    {text: '确定', onPress: value => this.postData(index, value)},
                                                ], 'default', '')}>
                                <Text style={{color: 'blue'}}>引航记事</Text>
                            </TouchableHighlight>

                        </View>
                    </View>

                </View>
            </TouchableHighlight>
        )
    }


    search() {
        this.setState({
            data: [],
        });
        this.loadData();
    }

    postData(index, msg) {
        const request = new Map();
        request.set('planid', this.state.data[index].ID);
        request.set('s_PILOT_RECORD', msg);

        fetch(postRealUrl(Urls['yhyjsUrl'], request), {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                Toast.success('提交成功', 1);
            })
            .catch(error => {
                Toast.success('提交失败', 1);
                this.setState({
                    isLoading: false
                });
            });

    }


}

const styles = StyleSheet.create({
    phone: {
        flex: 1,
        textDecorationLine: 'underline',
        color: '#0066FF',
    },
    text: {
        flex: 1
    },
    row: {
        flexDirection: 'column',
        justifyContent: 'center',
        padding: 10,
    },
});


export default PageYhyjs;